package org.hhf.ai.tools.funcalling;

import com.fasterxml.jackson.databind.JsonNode;
import org.hhf.ai.tools.pojo.Function;
import org.hhf.ai.tools.pojo.Tool;

import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 类函数注册器
 */
public class FunctionRegistry {
    public static final Map<String, FunctionTool> registeredFunctions = new HashMap<>();
    private static FunctionRegistry instance = new FunctionRegistry();

    public static FunctionRegistry getInstance() {
        if (instance == null) {
            instance = new FunctionRegistry();
        }
        return instance;
    }


    // 注册函数
    public void registerFunction(String functionName, FunctionTool function) {
        registeredFunctions.put(functionName, function);
    }

    // 获取注册的函数
    public FunctionTool getFunction(String functionName) {
        if (!instance.isFunctionRegistered(functionName)) {
            throw new IllegalArgumentException("Function '" + functionName + "' is not registered.");
        }
        return registeredFunctions.get(functionName);
    }

    // 判断函数是否已注册
    public boolean isFunctionRegistered(String functionName) {
        return registeredFunctions.containsKey(functionName);
    }

    /**
     * 获取所有tools
     * @return
     */
    public Object tools() {
        List<Tool> tools = new ArrayList<>();
        for (Map.Entry<String, FunctionTool> entry : registeredFunctions.entrySet()) {
            String name = entry.getKey();
            FunctionTool functionTool= entry.getValue();
            Tool tool = new Tool();
            Function function = new Function();
            function.setName(name);
            function.setDescription(functionTool.description());
            function.setParameters(functionTool.parameters());
            tool.setFunction(function);
            tools.add(tool);
        }
        return tools;
    }

    /**
     *
     * 函数调用
     *
     * @param functionName
     * @param params
     * @return
     * @throws InvocationTargetException
     * @throws IllegalAccessException
     */
    public String functionInvoker(String functionName, JsonNode params) {
        FunctionTool functionTool = instance.getFunction(functionName);
        return functionTool.execute(params);
    }
}